/*
 * CS_MARKET_ITEM_REG.cpp
 *
 *  Created on: 2013. 5. 22.
 *      Author: mega@gamevil.com
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NLogic/Bag.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Trade.h"
#include "../../NLogic/Static.h"
#include "../../NLogic/VirtualCurrency.h"
#include "../../NResource/Static.h"
//#include "../../NResource/ItemResource.h"
 #include "../../GameLog.h"

namespace ProjectZ { namespace NCommand {

void Command::CS_MARKET_ITEM_REG(User * pUser, ::Network::Packet * pPacket)
{
/*	CS_MARKET_ITEM_REG	0x1000
	{
		u64	item_seq;	// 아이템 seq
		u8	bag_type;	// 아이템 백타입
		u32	item_price;	// 유저가 입력한 판매 가격
	}

	/// 거래소 아이템 리스트 요청 : 인벤에서 선택해서 올림
	SC_MARKET_ITEM_REG	0x1001
	{
		s16 ack;	 /// 성공(1),  실패(-1), 수수료부족(603), 등록아이템 갯수 초과(602)
	}*/

	PREPARE_PACKET;

	uint64_t itemSeq	= 0;
	uint8_t bagType		= 0;
	uint32_t itemPrice	= 0;

	*pPacket >> itemSeq >> bagType >> itemPrice;

	if (true == NResource::Static::Instance().GetContentsOpenResource()->IsOpen(static_cast<int>(ContentsOpen::CHINA_CONTENTS)))
	{
		NResource::VIPResource::Data & vipData = NResource::Static::Instance().GetVIPResource()->GetData();

		if (vipData._VIP1_VP > pUser->GetUserInfo().reserve4)
		{
			::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
			* pAck << static_cast<int16_t>(ACK_NOT_VIP1);
			pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
			pUser->Send(pAck);
			return;
		}
	}

	NLogic::Bag * pBag = pUser->GetBag(static_cast<INVEN_BAG_TYPE>(bagType));
	if (NULL == pBag)
	{
		DEBUGLOG("CS_MARKET_ITEM_REG : pBag is NULL!!");
		return;
	}

	NLogic::Item * pItem = pBag->GetItem(itemSeq);
	if (NULL == pItem)
	{
		DEBUGLOG("CS_MARKET_ITEM_REG : pItem is NULL!!");
		return;
	}

	NLogic::Trade * pTrade = pUser->GetTrade();
	if (NULL == pTrade)
	{
		DEBUGLOG("CS_MARKET_ITEM_REG : pTrade is NULL!!");
		return;
	}

	// 거래소에 등록 가능한 아이템인지 확인
	if (1 != NResource::Static::Instance().GetItemResource()->getItemTradeType(pItem->GetData()))
	{
		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pAck << static_cast<int16_t>(ACK_MARKET_REGIST_NOT_ALLOW);
		pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
		pUser->Send(pAck);
		return;
	}

	// 아이템 등록 갯수 초과
	if (10 <= static_cast<int>(pTrade->GetTradeItemTree().size()))
	{
		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pAck << static_cast<int16_t>(ACK_MARKET_REGISTER_OVER_FLOW);
		pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
		pUser->Send(pAck);
		return;
	}

	// 수수료 계산 (2%)
	int commission = itemPrice * 0.02;

	// 수수료 부족
	if (commission > static_cast<int>(pUser->GetCharacterInfo().gold))
	{
		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pAck << static_cast<int16_t>(ACK_NOT_ENOUGH_GOLD);
		pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
		pUser->Send(pAck);
		return;
	}

	// 아이템 귀속여부 확인 (2=착귀, 3=획귀)
	if (pItem->GetData().buy_use == 2 || pItem->GetData().buy_use == 3)
	{
		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pAck << static_cast<int16_t>(ACK_MARKET_REGIST_NOT_ALLOW);
		pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
		pUser->Send(pAck);
		return;
	}

//	pUser->GetCharacterInfo().gold -= commission;
	NLogic::NFunction::ModifyGold(pUser, commission * -1);
	NGameLog::LogGoldInfo(pUser, REG_TRADE, commission * -1);

	// 시퀀스, 등록날짜, 등록종료날짜를 가져온다.
	uint64_t tradeSeq		= 0;
	uint64_t tradeSelfSeq	= 0;
	uint64_t regDate		= 0;
	uint64_t limitDate		= 0;

	{
		// 거래 아이템 등록
		::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
		clsAuto->SetQueryType(::Database::Command::S_PROCEDURE);
		clsAuto->MakeQuery("call sp_insert_trade_item(%d,%d,%d,'%s',%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
				pUser->GetUserSeq(),
				pUser->GetCharacterInfo().characterseq,
				itemPrice,
				//pUser->GetUserInfo().nickname.c_str(),
				pUser->GetUserNickName().c_str(),
				pItem->GetData().bag_type,
				pItem->GetData().bag_slot_number,
				pItem->GetData().quantity,
				pItem->GetData().class_type,
				pItem->GetData().sub_type,
				pItem->GetData().tid,
				pItem->GetData().iconidx,
				pItem->GetData().item_type,
				pItem->GetData().cur_duration,
				pItem->GetData().max_duration,
				pItem->GetData().set_type,
				pItem->GetData().non_identity,
				pItem->GetData().cur_refine_step,
				pItem->GetData().quality,
				pItem->GetData().level,
				pItem->GetData().eff_type[0],
				pItem->GetData().eff_pos[0],
				pItem->GetData().eff_value[0],
				pItem->GetData().eff_type[1],
				pItem->GetData().eff_pos[1],
				pItem->GetData().eff_value[1],
				pItem->GetData().eff_type[2],
				pItem->GetData().eff_pos[2],
				pItem->GetData().eff_value[2],
				pItem->GetData().eff_type[3],
				pItem->GetData().eff_pos[3],
				pItem->GetData().eff_value[3],
				pItem->GetData().eff_type[4],
				pItem->GetData().eff_pos[4],
				pItem->GetData().eff_value[4],
				pItem->GetData().eff_type[5],
				pItem->GetData().eff_pos[5],
				pItem->GetData().eff_value[5],
				pItem->GetData().eff_type[6],
				pItem->GetData().eff_pos[6],
				pItem->GetData().eff_value[6],
				pItem->GetData().open_upgrade_stone_slot,
				pItem->GetData().ability_enhance_rate,
				pItem->GetData().max_enhance_step,
				pItem->GetData().buy_use,
				pItem->GetData().evolve_step,
				pItem->GetData().evolve_max,
				pItem->GetData().evolve_point,
				pItem->GetData().evolve_percent,
				pItem->GetData().evolve_value,
				pUser->GetUserSeq() % 10);

		DEBUGLOG("%s INSERT TRADE ITEM QUERY : %s", __FUNCTION__, clsAuto->GetQueryString());

		if (false == ::Database::GETSESSION()->SyncExecute(static_cast<int>(DatabaseType::TRADE_MASTER), clsAuto))
		{
			DEBUGLOG("CS_MARKET_ITEM_REG : false == ::Database::GETSESSION()->SyncExecute(1, clsAuto)");
			return;
		}

		if (clsAuto->GetErrorIdx() != 0)
		{
			DEBUGLOG("CS_MARKET_ITEM_REG : clsAuto->GetErrorIdx() != 0");
			return;
		}

		while (clsAuto->Next())
		{
			clsAuto->GetRecord() >> tradeSeq >> tradeSelfSeq >> regDate >> limitDate;
		}
	}

	// 데이터 생성
	NLogic::Trade::TradeItem::Data clsData;
	clsData.reg_slot_seq	= pUser->GetCharacterInfo().characterseq;
	clsData.reg_date		= regDate;
	clsData.limit_date		= limitDate;
	clsData.item_price		= itemPrice;
	clsData.status			= 0;
	clsData.item			= pItem->GetData();

	NLogic::Trade::TradeItem * pTradeItem = NLogic::Static::InstancePtr()->GETTRADEITEMPOOL()->NEW();
	pTradeItem->Open_FromDatabase(tradeSeq, tradeSelfSeq, clsData, pUser);
	pTrade->AddTradeItemData(pTradeItem);

	// 거래소 등록 아이템 삭제 처리
	pBag->PopItem(itemSeq);
	pItem->DeleteDatabaseItemInfo(NLogic::Item::ItemStatus::EM_ITEM_STATUS_REG_MARKET);

	// 응답
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	*pAck << pUser->GetCharacterInfo().gold;
	*pAck << pUser->GetVirtualCurrency()->GetZen();
	pAck->MakePacket(CMD_SC_MARKET_ITEM_REG);
	pUser->Send(pAck);

	// 로그 기록
	std::string itemName = NResource::Static::InstancePtr()->GetItemResource()->GetItemName(pTradeItem->GetData().item);
	NGameLog::LogTradeRegInfo(pUser,
			itemPrice,
			pTradeItem->GetData().item.class_type,
			pTradeItem->GetData().item.sub_type,
			tradeSeq,
			regDate,
			pTradeItem->GetData().item.quality,
			itemName.c_str());

}

} /*NCommand*/ } /*ProjectZ*/
